from flask import current_app, render_template, session, request, g
from flask.json import jsonify

from info import constants, db, user_is_login
from info.models import News, User, Comment, CommentLike
from info.modules.news import news_blue
from info.utils.response_code import RET


@news_blue.route('/<int:news_id>')
@user_is_login
def new_detail(news_id):
    # 获取session，判断用户是否登录
    # 当前登录用户是否关注当前新闻作者
    is_followed = False
    # 判断用户是否收藏过该新闻
    is_collected = False
    # if g.user:
    #     if news in g.user.collection_news:
    #         is_collected = True
    #     if news.user.followers.filter(User.id == g.user.id).count() > 0:
    #         is_followed = True
    user_id = session.get('user_id')
    user = None  # type User
    if user_id:
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)
    try:
        #
        click_datas = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
    click_data_list = []
    for click_data in click_datas:
        click_data_list.append(click_data.to_basic_dict())

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
    data = None

    comments = None
    try:
        comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)

    is_collected = False
    # 判断用户是否收藏过该新闻
    comment_like_ids = []
    if user:
        # 判断用户是否收藏
        if news in user.collection_news:
            is_collected = True
        # 如果当前用户已登录
        if news.user:
            if news.user.followers.filter(User.id == g.user.id).count() > 0:
                is_followed = True
        try:
            comment_ids = [comment.id for comment in comments]
            if len(comment_ids) > 0:
                # 取到当前用户在当前新闻的所有评论点赞的记录
                comment_likes = CommentLike.query.filter(CommentLike.comment_id.in_(comment_ids),
                                                         CommentLike.user_id == user.id).all()
                # 取出记录中所有的评论id
                comment_like_ids = [comment_like.comment_id for comment_like in comment_likes]
        except Exception as e:
            current_app.logger.error(e)
    comment_list = []
    for item in comments:
        comment_dict = item.to_dict()
        # comment_list.append(comment_dict)
        comment_dict["is_like"] = False
        # 判断用户是否点赞该评论
        if user and item.id in comment_like_ids:
            comment_dict["is_like"] = True
        comment_list.append(comment_dict)

    if news:
        data = {
            'news': news.to_dict(),
            'user_info': user.to_dict() if user else None,
            'click_news': click_data_list,
            'is_collected': is_collected,
            'comments': comment_list,
            'is_followed':is_followed
        }
    return render_template('news/detail.html', data=data)


@news_blue.route("/news_collect", methods=['POST'])
def news_collect():
    """
    1、获取参数
    2、校验参数
    3、数据库操作
    4、返回响应
    :return:
    """
    # 获取数据
    params = request.json
    news_id = params.get('news_id')
    action = params.get('action')

    # 用户是否登录
    user_id = session.get('user_id')
    user = None  # type User
    if user_id:
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)

    # 校验数据
    if not news_id:
        return jsonify(errno=RET.DATAERR, errmsg='参数不足')
    if action not in ['collect', 'cancel_collect']:
        return jsonify(errno=RET.DATAERR, errmsg='参数不足')
    if not user:
        return jsonify(errno=RET.LOGINERR, errmsg='用户未登录')

    # 查询新闻
    try:
        news = News.query.get(news_id)
    except:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据失败")

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="新闻数据不存在")
    # 添加收藏，取消收藏
    if action == 'collect':
        user.collection_news.append(news)
    else:
        user.collection_news.remove(news)
    # 数据提交，向数据库插入数据
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='数据插入错误')
    # 返回成功响应
    return jsonify(errno=RET.OK, errmsg='操作成功')


@news_blue.route('/news_comment', methods=["POST"])
def add_news_comment():
    """
    新闻评论：
    1、获取参数
    2、校验参数
    :return:
    """

    # 获取参数
    params = request.json
    news_id = params.get('news_id')
    comment = params.get('comment')
    parent_id = params.get('parent_id')

    # 获取session，判断用户是否登录
    user_id = session.get('user_id')
    user = None  # type User
    if user_id:
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)

    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    # 对参数进行校验
    if not all([news_id, comment]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")

    # 查询新闻
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")
    # 校验新闻数据是否存在
    if not news:
        return jsonify(errno=RET.NODATA, errmsg="新闻不存在")

    # 增加评论对象
    comments = Comment()
    comments.news_id = news_id
    comments.user_id = user_id
    comments.content = comment
    if parent_id:
        comments.parent_id = parent_id
    # 向数据库提交数据
    try:
        db.session.add(comments)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DATAERR, errmsg="数据库执行错误")
    # 返回成功响应

    return jsonify(errno=RET.OK, errmsg="评论成功", data=comments.to_dict())


@news_blue.route('/comment_like', methods=['POST'])
def comment_like():
    """
    点赞
    :return:
    """

    # 获取session，判断用户是否登录
    user_id = session.get('user_id')
    user = None  # type User
    if user_id:
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)

    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    # 获取参数
    params = request.json
    comment_id = params.get('comment_id')
    action = params.get('action')
    if not all([comment_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if action not in ['add', 'remove']:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        comment_id = int(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        comment_str = Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    if not comment_str:
        return jsonify(errno=RET.NODATA, errmsg="评论不存在")

    if action == 'add':
        # 点赞
        comment_like_str = CommentLike()
        comment_like_str.comment_id = comment_id
        comment_like_str.user_id = user_id
        db.session.add(comment_like_str)
        comment_str.like_count += 1
    else:
        comment_like_object = CommentLike.query.filter(
            CommentLike.user_id == user_id,
            CommentLike.comment_id == comment_id).first()
        if comment_like_object:
            db.session.delete(comment_like_object)
            comment_str.like_count -= 1

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")
    return jsonify(errno=RET.OK, errmsg="成功")


@news_blue.route('/followed_user', methods=["POST"])
@user_is_login
def followed_user():
    """关注/取消关注用户"""
    if not g.user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    user_id = request.json.get("user_id")
    action = request.json.get("action")

    if not all([user_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if action not in ("follow", "unfollow"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 查询到关注的用户信息
    try:
        target_user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据库失败")

    if not target_user:
        return jsonify(errno=RET.NODATA, errmsg="未查询到用户数据")

    # 根据不同操作做不同逻辑
    if action == "follow":
        if target_user.followers.filter(User.id == g.user.id).count() > 0:
            return jsonify(errno=RET.DATAEXIST, errmsg="当前已关注")
        target_user.followers.append(g.user)
    else:
        if target_user.followers.filter(User.id == g.user.id).count() > 0:
            target_user.followers.remove(g.user)

    # 保存到数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据保存错误")

    return jsonify(errno=RET.OK, errmsg="操作成功")
